package com.ge.boot10secruity.config;

import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
public class AppSecurityConfiguration {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 配置请求认证
        http.authorizeHttpRequests(registry -> {
            // 访问首页无需认证
            registry.requestMatchers("/").permitAll()
                    // 其他请求需要认证
                    .anyRequest().authenticated();
        });

        // 保留原有的表单登录
        // http.formLogin(withDefaults());

        // 自定义登录页
        http.formLogin(formLogin -> {
            // 登录页的访问请求为/login，且无需认证即可访问
            formLogin.loginPage("/login").permitAll();
        });

        return http.build();
    }

    @Bean
    UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {

        // 定义用户张三
        UserDetails ZhangSan = User.withUsername("ZhangSan")
                .password(passwordEncoder.encode("123456"))
                .roles("admin", "common")
                .authorities("file_read", "file_write")
                .build();

        // 定义用户李四
        UserDetails LiSi = User.withUsername("LiSi")
                .password(passwordEncoder.encode("123456"))
                .roles("hr")
                .authorities("file_read")
                .build();

        // 定义用户王五
        UserDetails WangWu = User.withUsername("WangWu")
                .password(passwordEncoder.encode("123456"))
                .roles("admin")
                .authorities("file_write")
                .build();

        // 返回InMemoryUserDetailsManager对象，传入定义的用户
        return new InMemoryUserDetailsManager(ZhangSan, LiSi, WangWu);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
